﻿using LearnASPNETCore.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCore.Services
{
    public class DepartmentService : IDepartmentService
    {
        private readonly List<Department> _departments = new List<Department>();

        public DepartmentService()
        {
            _departments.Add(new Department
            {
                Id = 1,
                Name = "HR",
                EmployeeCount = 16,
                Location = "Beijing"
            });
            _departments.Add(new Department
            {
                Id = 2,
                Name = "RD",
                EmployeeCount = 52,
                Location = "Shanghai"
            });
            _departments.Add(new Department
            {
                Id = 3,
                Name = "Sales",
                EmployeeCount = 200,
                Location = "China"
            });
        }


        public Task<IEnumerable<Department>> GetAll()
        {
            return Task.Run(() => _departments.AsEnumerable());
        }



        public Task<Department> GetById(int id)
        {
            return Task.Run(() => _departments.FirstOrDefault(x => x.Id == id));
        }

        //获取公司总体情况
        public Task<CompanySummary> GetCompanySummary()
        {
            return Task.Run(() =>
            {
                return new CompanySummary
                {
                    //Lambda不是很明白可以看看我的博客：https://blog.csdn.net/wujuncheng1996/article/details/105518707
                    //员工总数：每个部门的人数求和
                    EmployeeCount = _departments.Sum(x => x.EmployeeCount),
                    //员工平均数：调用Average平均数函数，计算后从double（小数）转换为整型。
                    AverageDepartmentEmployeeCount = (int) _departments.Average(x => x.EmployeeCount)
                };
            });
        }
        public Task Add(Department department)
        {
            //添加的部门ID为现有部门ID最大值+1
            department.Id = _departments.Max(x => x.Id) + 1;
            //将部门添加到部门集合
            _departments.Add(department);
            return Task.CompletedTask;
        }
    }
}